package org.springblade.common.utils;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springblade.common.constant.NumberConstants;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * @author dengzhongtao
 * @date 2021/11/11
 */
@Slf4j
public class ValidateUtils {
	private static Validator validator = Validation.buildDefaultValidatorFactory()
		.getValidator();

	public static <T> Map<String, StringBuilder> validate(T obj){
		log.info("[ValidateUtils.validate]参数校验开始");
		Map<String, StringBuilder> errorMap = null;
		Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
		if(set != null && set.size() >0 ){
			errorMap = Maps.newHashMap();
			String property;
			for(ConstraintViolation<T> cv : set){
				property = cv.getPropertyPath().toString();
				if(errorMap.get(property) != null){
					errorMap.get(property).append(",").append(cv.getMessage());
				}else{
					StringBuilder sb = new StringBuilder();
					sb.append(cv.getMessage());
					errorMap.put(property, sb);
				}
			}
		}
		log.info("[ValidateUtils.validate]参数校验结束errorMap:{}", errorMap);
		return errorMap;
	}


	/**
	 * 判断数据库操作是否成功
	 * @param record
	 * @return
	 */
	public static boolean isDbOperateSuccess(int record){
		return NumberConstants.DB_OPERATE_RECORD == record;
	}

	/**
	 * 判断数据库操作是否成功
	 * @param record record
	 * @return boolean
	 */
	public static boolean isDbOperateFailure(int record){
		return !isDbOperateSuccess(record);
	}


	/**
	 * 密码规则校验
	 * @param password
	 * @return
	 */
	public static boolean validatePassword(String password){
		String regExp = "^(?![a-zA-Z]+$)(?![0-9]+$)(?![!@#$%^&*_-]+$)(?![a-zA-Z0-9]+$)(?![a-zA-Z!@#$%^&*_-]+$)(?![0-9!@#$%^&*_-]+$)[a-zA-Z0-9!@#$%^&*_-]{8,20}$";
		return password.matches(regExp);
	}


	/**
	 * 日期验证
	 * @param value  字符串
	 * @param format 格式
	 * @return
	 */
	public static boolean validateDate(String value,String format){
		SimpleDateFormat sdf = null;
		//指定从所传字符串的首位开始解析
		ParsePosition pos = new ParsePosition(0);
		if(value == null || StringUtils.isEmpty(format)){
			return false;
		}
		try {
			sdf = new SimpleDateFormat(format);
			sdf.setLenient(false);
			Date date = sdf.parse(value,pos);
			if(date == null){
				return false;
			}else{
				//更为严谨的日期,如2011-03-024认为是不合法的
				if(pos.getIndex() > sdf.format(date).length()){
					return false;
				}
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}


	/***
	 * 判断字符串是否为数字（小数点最多三位小数）
	 *
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str){
		if(StringUtils.isEmpty(str)){
			return false;
		}
		String reg = "^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,3})?$";
		return str.matches(reg);
	}

	/***
	 * 判断输入的数字是否为正浮点数
	 * @param obj
	 * @return
	 */
	public static boolean judgeDecimal(Object obj){
		String floatRegex = "^(0(\\.\\d*[1-9]+\\d*)?)$|^([1-9]\\d*)(\\.\\d*)?$";
		boolean flag = false;
		try {
			if (obj != null) {
				String source = obj.toString();
				// 判断是否是正浮点数
				if (Pattern.matches(floatRegex, source)) {
					flag = true;
				}
			}
		} catch (Exception e) {
			log.info("[ValidateUtils.judgeDecimal]判断异常e:{}", e);
		}
		return flag;
	}


}
